package otherservlet;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.dbutils.QueryRunner;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import bean.Commodity;
import bean.UserBean;
import bean.Cart;
import service.ComodityService;
import service.UserService;

/**
 * Servlet implementation class AddtocartServlet
 */
@WebServlet("/AddtocartServlet")
public class AddtocartServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddtocartServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	     String cmdyid=request.getParameter("cmdyid");
	     UserBean user=(UserBean)request.getSession().getAttribute("user_login");
	     
	     
		// Commodity commodity=com.getCommodityByID(cmdyid);
		 
		 UserService us=new UserService();
		 
		 if(user!=null) {
			 try {
					 String userid=user.getUserid();
				     int buynum=Integer.parseInt(request.getParameter("buynum"));
				     ComodityService com=new ComodityService();
				     
					Cart cart1=us.findCartRecord(userid, cmdyid);
					if(cart1==null) {
						us.AddtoCart(cmdyid, buynum, userid);
						
						
					} else {
						us.UpdateCart(cmdyid, buynum, userid);
						
					}
					response.getWriter().print("{\"msg\":\"1\"}");
					
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		 }else {
			 
			 response.getWriter().print("{\"msg\":\"3\"}");
		 }
		 
		 
		 
		 
		 
	
		 
	    
	     
	}

}
